package com.cirkana.viewer.location.select;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;

import com.cirkana.CirkanaActivity;
import com.cirkana.serial.SerializationException;
import com.cirkana.viewer.R;

public class SelectLocationActivity extends CirkanaActivity {

	public static final int RESULT_CHANGELOCATION_OK = 0;

	private WebView mapWebView;
	private SelectLocationCommunicator comm;
	private Button changeLocation;

	private SelectLocationPassData data;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selectlocation);

		this.mapWebView = (WebView) findViewById(R.id.select_location_map);
		this.changeLocation = (Button) findViewById(R.id.select_location_change_location);

		this.data = (SelectLocationPassData) getRequest(SelectLocationPassData.class);
		this.comm = new SelectLocationCommunicator();
		if (this.data.hasLocation())
			this.comm.setLocation(this.data.getLatitude(), this.data
					.getLongitude());

		this.mapWebView.getSettings().setJavaScriptEnabled(true);
		this.mapWebView.loadUrl("file:///android_asset/locator.html");
		this.mapWebView.addJavascriptInterface(comm, "comm");

		this.changeLocation.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				data.setLatitude(comm.getLatitudeValue());
				data.setLongitude(comm.getLongitudeValue());
				try {
					setResponse(RESULT_CHANGELOCATION_OK, data);
				} catch (SerializationException e) {
					openMessageBox("Error", e.getMessage());
				}
				finish();
			}
		});

	}

	private class SelectLocationCommunicator {
		private double latitude;
		private double longitude;

		protected SelectLocationCommunicator() {
		}

		@SuppressWarnings("unused")
		public String getLatitude() {
			return Double.toString(latitude);
		}

		@SuppressWarnings("unused")
		public void setLatitude(String latitude) {
			this.latitude = Double.parseDouble(latitude);
		}

		@SuppressWarnings("unused")
		public String getLongitude() {
			return Double.toString(longitude);
		}

		@SuppressWarnings("unused")
		public void setLongitude(String longitude) {
			this.longitude = Double.parseDouble(longitude);
		}

		protected void setLocation(Double latitude, Double longitude) {
			this.latitude = latitude;
			this.longitude = longitude;
		}

		protected Double getLatitudeValue() {
			return this.latitude;
		}

		protected Double getLongitudeValue() {
			return this.longitude;
		}
	}

}
